package stcu.forms;

import stcu.*;
import stcu.robjects.*;
import com.nvlled.route.*;

import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class MainForm extends javax.swing.JFrame 
        implements Group.Listener {

    private JFrame self = this;
    private Group defaultGroup;
    private DefaultListModel<String> userListModel;
    //private DefaultListModel<String> groupListModel;
    private DefaultListModel<GroupAdd> groupListModel;
    private Map<String, GroupAdd> groups;
    private Client client;

    public MainForm() {
        initComponents();
    }

    public MainForm(Group group, Client client) {
        initComponents();
        configFrame();

        this.client = client;
        defaultGroup = group;
        messageLogText.setEditable(false);
        userListModel = new DefaultListModel<String>();
        groupListModel = new DefaultListModel<GroupAdd>();
        groups = new HashMap<String, GroupAdd>();

        userList.setModel(userListModel);
        groupList.setModel(groupListModel);

        handleButtons();
        defaultGroup.setListener(this);
        monitorGroups();

        group.listMembers();
        listGroups();
    }

    private void configFrame() {
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                ClientAuth auth = client.getAuth();

                defaultGroup.leave();
                auth.logout();
            }
        });
    }

    private void listGroups() {
        ObjectRouter router = client.getRouter();
        router.deliver(new GroupList(), "default");
    }

    private void handleButtons() {
        sendButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String message = messageText.getText();
                messageText.setText("");
                defaultGroup.send(message);
            }
        });
        createButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                GroupAccess access = client.getAccess();
                ClientAuth auth = client.getAuth();
                CreateGroupForm form = new CreateGroupForm(auth.getLoginId(), access);
                form.setVisible(true);
            }
        });
        joinButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                GroupAdd groupInfo = (GroupAdd) groupList.getSelectedValue();
                if (groupInfo == null) {
                    return;
                }

                joinButton.setEnabled(false);
                GroupAccess access = client.getAccess();
                ClientAuth auth = client.getAuth();

                try {
                    Group group = access.join(auth.getLoginId(), groupInfo.getGroupId());
                    final ChatForm form = new ChatForm(group); 
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            form.setVisible(true);
                        }
                    });
                } catch (GroupOperationException err) {
                    JOptionPane.showMessageDialog(self, err.getMessage());
                }
                joinButton.setEnabled(true);
            }
        });
    }

    private void monitorGroups() {
        ObjectReceiver<GroupAdd> receiverAdd = new ObjectReceiver<GroupAdd>() {
            public void receive(GroupAdd group) {
                ObjectRouter router = client.getRouter();
                AddressTable table = router.getTable();
                table.store(group.getGroupId(), group.getAddress());
                groups.put(group.getGroupId(), group);
                groupListModel.addElement(group);
            }
        };
        ObjectReceiver<GroupDel> receiverDel = new ObjectReceiver<GroupDel>() {
            public void receive(GroupDel group) {
                groups.remove(group.getGroupId());
                groupListModel.removeElement(group);
            }
        };
        ObjectRouter router = client.getRouter();
        router.subscribe(GroupAdd.class, receiverAdd);
        router.subscribe(GroupDel.class, receiverDel);
    }

    public void messageReceived(GroupMessage message) {
        String line = message.getSender() + ": " +
            message.getMessage();
        messageLogText.append(line+"\n");
    }

    public void memberJoined(MemberAdd member) {
        String name = member.getName();
        if (member.isNewMember()) {
            String line = name + " logged in";
            messageLogText.append(line+"\n");

        }
        if (! userListModel.contains(name)) {
            userListModel.addElement(name);
        }
    }

    public void memberLeft(MemberDel member) {
        String line = member.getName() + " logged out";
        messageLogText.append(line+"\n");
        userListModel.removeElement(member.getName());

        String name = member.getName();
        GroupDemux demux = client.getAccess().getDemux();
        for (Group group: demux.getSubscribedGroups()) {
            group.receive(new GroupLeave(name, group.getId()));
        }
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        sendButton = new javax.swing.JButton();
        messageText = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        messageLogText = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        userList = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        groupList = new javax.swing.JList();
        createButton = new javax.swing.JButton();
        joinButton = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        logoutMenu = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

        sendButton.setText("Send");

        jLabel1.setText("Online users:");

        messageLogText.setColumns(20);
        messageLogText.setRows(5);
        jScrollPane1.setViewportView(messageLogText);

        userList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(userList);

        jScrollPane3.setViewportView(jScrollPane2);

        jLabel2.setText("Groups:");

        groupList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane4.setViewportView(groupList);

        createButton.setText("Create Group");

        joinButton.setText("Join Group");

        logoutMenu.setText("File");

        jMenu2.setText("Logout");
        logoutMenu.add(jMenu2);

        jMenuBar1.add(logoutMenu);

        //setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(messageText, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton))
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3)
                    .addComponent(joinButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane4)
                    .addComponent(createButton, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(messageText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(sendButton)))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(joinButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(createButton)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton createButton;
    private javax.swing.JList groupList;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JButton joinButton;
    private javax.swing.JMenu logoutMenu;
    private javax.swing.JTextArea messageLogText;
    private javax.swing.JTextField messageText;
    private javax.swing.JButton sendButton;
    private javax.swing.JList userList;
    // End of variables declaration//GEN-END:variables
}
